<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.*" %>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'doFirst.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
   <%!
  String newName(String name){
  int pos = name.lastIndexOf('.');
  String prefix = name.substring(pos==-1?0:pos);
  return UUID.randomUUID()+prefix;//随机生成一个32位的文件名！
  }
   %>
  <%
  DiskFileItemFactory factory = new DiskFileItemFactory();
  ServletFileUpload upload = new ServletFileUpload(factory);
  upload.setHeaderEncoding("utf-8");//设置字符集
  List<FileItem> fields = upload.parseRequest(request);//拿到所有的域
  String picPath =application.getRealPath("news/images") ;//拿到的图片准备存到哪里（存放路径）
  for(FileItem f:fields){
  	if(f.isFormField()){
  		out.print("<h1>这是表单域：" + f.getFieldName() + ",value" + f.getString("utf-8")+"</h1>");
  		//从表单域获得对应的值并添加至news对象中
  		//后续再对news对象进行处理（insert into 语句）
  	}else{
  		if(f.getName()==""){
  			continue;
  		}
  		out.print("<h1>文件域，文件名是"+f.getName()+"</h1>");
  		String newFileName = newName(f.getName());
  		f.write(new java.io.File(picPath,newFileName));
  		out.print("<img src = 'news/images/"+newFileName+"'/>");
  	
  	}
  
  }
  
   %>
    



  </body>
</html>
